import { login } from "@/apis/user";
import axios from "axios";
import { Dialog, Toast } from "react-vant";
import { getDeviveCode, initWXConfig } from "./index";

const http = axios.create();
http.defaults.timeout = 10000;

// 请求拦截
http.interceptors.request.use(
    async (config: any) => {
        const openid = localStorage.getItem("openId") || undefined;
        const userId = localStorage.getItem("userId") || undefined;

        //如果存在，为deviceCode 设置openid
        if (openid) window.deviceCode = openid;

        //添加设备code
        if (!window.deviceCode) {
            const deviceCode = await getDeviveCode();
            window.deviceCode = deviceCode;
        }

        //前置登录
        if (!userId) {
            const userId = await login();
            userId && localStorage.setItem("userId", userId);
            initWXConfig();
        }

        config.headers["deviceCode"] = window.deviceCode || "";
        config.headers["userId"] = userId || "";
        config.headers["openId"] = openid || window.deviceCode
        return config;
    },
    (error: any) => {
        console.log(error); // for debug
        return Promise.reject(error);
    }
);

// 响应拦截器
http.interceptors.response.use(
    (response) => {
        const res = response.data;
        if (res?.msg === "登录错误") {
            localStorage.clear();
            Dialog.alert({
                title: '授权异常',
                message: '授权异常，请重新登录',
                onConfirm: function () {
                    window.location.href = '/'
                }
            })
        }
        if (res?.state === "fail") {
            res?.msg && Toast(res?.msg)
            return Promise.reject(res)
        };

        return res;
    },
    (error) => {
        return Promise.reject(error);
    }
);

export default http;
